// Modules to control application life and create native browser window
const {
  app,
  BrowserWindow,
  ipcMain,
  Menu,
  dialog,
  globalShortcut,
} = require("electron");
const { AppWindow } = require("./appWindow");
const DataStore = require("./musicDataStore");
// const path = require("path");

const myStore = new DataStore({ name: "Music Data" });
function createMainWindow(config, fileLocation) {
  Menu.setApplicationMenu(null);
  const mainWindow = new AppWindow(config, fileLocation);

  globalShortcut.register("CommandOrControl+Shift+i", () => {
    mainWindow.webContents.openDevTools();
  });

  mainWindow.webContents.on("did-finish-load", () => {
    mainWindow.send("getTracks", myStore.getTracks());
  });

  ipcMain.on("add-music-window", () => {
    const addWindow = new AppWindow(
      {
        width: 500,
        height: 400,
        parent: mainWindow,
      },
      "./renderer/add.html"
    );
  });
  ipcMain.on("add-tracks", (_event, tracks) => {
    const updateTracks = myStore.addTracks(tracks).getTracks();
    mainWindow.send("getTracks", updateTracks);
  });
  ipcMain.on("delete-track", (_event, trackId) => {
    const updateTracks = myStore.deleteTrack(trackId).getTracks();
    mainWindow.send("getTracks", updateTracks);
  });
  ipcMain.on("open-music-file", (event) => {
    dialog
      .showOpenDialog({
        properties: ["openFile", "multiSelections"],
        filters: [{ name: "Music", extensions: ["mp3"] }],
      })
      .then((result) => {
        const { filePaths } = result;
        if (filePaths.length > 0) {
          event.sender.send("select-file", filePaths);
        }
      });
  });
}

app.whenReady().then(() => {
  createMainWindow({}, "./renderer/index.html");

  app.on("activate", function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0)
      createMainWindow({}, "./renderer/index.html");
  });
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", function () {
  if (process.platform !== "darwin") app.quit();
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
